#include <rtthread.h>
#include <rtdevice.h>

#include "lwip/sockets.h"

#define SERVER_PORT_TCP			6666
#define TCP_BACKLOG 10

char recvbuf[512];
/* 在sock_fd 进行监听，在 new_fd 接收新的链接 */
int sock_fd, new_fd;

static void tcpecho_thread(void *arg)
{
	char *str;

	/* 自己的地址信息 */
	struct sockaddr_in my_addr;
	/*	连接者的地址信息*/
	struct sockaddr_in their_addr;
	int sin_size;

	struct sockaddr_in *cli_addr;

	/* 1 、创建socket  */
	if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		perror("socket is error\r\n");
		//exit(1);
	}

	memset(&my_addr, 0, sizeof(their_addr));
	/* 主机字节顺序 */
	/* 协议 */
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(6666);
	/* 当前IP 地址写入 */
	my_addr.sin_addr.s_addr = INADDR_ANY;

	/* bind 绑定*/
	if(bind(sock_fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
	{
		perror("bind is error\r\n");
		//exit(1);
	}

	/* 开始监听 */
	if(listen(sock_fd, TCP_BACKLOG) == -1)
	{
		perror("listen is error\r\n");
		//exit(1);
	}

	printf("start accept\n");


	/* accept() 循环 */
	while(1)
	{
		sin_size = sizeof(struct sockaddr_in);

		if((new_fd = accept(sock_fd, (struct sockaddr *)&their_addr, (socklen_t *)&sin_size)) == -1)
		{
			perror("accept");
			continue;
		}

		cli_addr = malloc(sizeof(struct sockaddr));

		printf("accept addr\r\n");

		if(cli_addr != NULL)
		{
			memcpy(cli_addr, &their_addr, sizeof(struct sockaddr));
		}

		//处理目标
		int ret;
		
		char *buf = "hello! I'm server!";

		while(1)
		{
			//接收数据
			if((ret = recv(new_fd, recvbuf, sizeof(recvbuf), 0)) == -1){
				printf("recv error \r\n");
				return ;
			}
			printf("recv :\r\n");
			printf("%s", recvbuf);
			printf("\r\n");
			rt_thread_mdelay(200);
			//发送数据
			if((ret = send(new_fd, buf, strlen(buf) + 1, 0)) == -1)
			{
				perror("send : ");
			}

			rt_thread_mdelay(200);
		}

		

		close(new_fd);
	}

	
	return ;
}

void tcpecho_init(void)
{
	sys_thread_new("tcpecho_thread", tcpecho_thread, NULL, 5*1024, 3);
}